package org.example.proxy;

import org.example.Loadbalance.LoadBalance;
import org.example.common.Invocation;
import org.example.common.Url;
import org.example.protocol.HttpClient;
import org.example.register.MapRegister;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;

public class ServiceProxy implements InvocationHandler {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String serviceName = method.getDeclaringClass().getName();
        Invocation invocation = new Invocation(serviceName, method.getName(), "1.0"
                , method.getParameterTypes(),args);

        HttpClient httpClient = new HttpClient();
        //服务发现
        List<Url> urls = MapRegister.get(serviceName);

        //负载均衡
        Url random = LoadBalance.random(urls);

        //服务调用
        // 添加重试机制
        String localhost = null;
        try {
            localhost = httpClient.send(random.getHostName(),random.getPort() , invocation);
        } catch (Exception e) {
            throw new RuntimeException(e);

        }
        return localhost;
    }
}
